//
//  SEPatientListViewController.swift
//  SmartEyeForPatient
//
//  Created by qdsg on 2021/4/15.
//

import UIKit

enum SEPatientListViewControllerType {
    case list
    case select

    var title: String {
        switch self {
        case .list:
            return "就诊人管理"
        case .select:
            return "选择就诊人"
        }
    }

}

class SEPatientListViewController: SEBaseViewController {

    @IBOutlet weak var tableView: UITableView! {
        didSet {
            tableView.isHidden = true
            tableView.tableFooterView = tableFooterView
            tableView.rowHeight = 80
            tableView.register(UINib(nibName: SEPatientListCell.className, bundle: nil), forCellReuseIdentifier: SEPatientListCell.reuseId)
        }
    }

    let patientListType: SEPatientListViewControllerType
    var selectedHandler: ((_ model: SEPatientDetailViewModel) -> Void)?
    var viewModel = SEPatientListViewModel(withLoading: true)

    init(with type: SEPatientListViewControllerType) {
        self.patientListType = type
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = patientListType.title
        requestPatientList()
        // Do any additional setup after loading the view.
    }

    override func setupUI() {
        super.setupUI()
        viewModel.updateData = { status in
            switch status {
            case .success:
                self.tableView.isHidden = false
                self.tableView.reloadData()
            case .auth(let msg):
                self.presentLoginViewController(selector: #selector(self.requestPatientList)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.setDefaultPatientHandler = { status in
            switch status {
            case .success:
                self.requestPatientList()
            case .auth(let msg):
                self.presentLoginViewController(selector: #selector(self.requestSetDefaultPatient)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }
    }

    lazy var tableFooterView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.screenWidth, height: 78))
        let btnView = SERegistrationConfirmBtnView(frame: CGRect(x: 15, y: 30, width: UIScreen.screenWidth - 30, height: 48))
        btnView.delegate = self
        btnView.title = "添加就诊人"
        view.addSubview(btnView)
        return view
    }()

    private func pushToPatientDetailViewController(_ type: SEPatientDetailViewControllerEditType) {
        let vc = SEPatientDetailViewController(with: viewModel.selectedlistItem, editType: type)
        vc.submitSuccessHandler = {
            self.requestPatientList()
        }
        navigationController?.pushViewController(vc, animated: true)
    }

}

// MARK: - UITableViewDataSource, UITableViewDelegate

extension SEPatientListViewController: UITableViewDataSource, UITableViewDelegate {

    // MARK: - UITableViewDataSource

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.numberOfSection
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SEPatientListCell.reuseId, for: indexPath) as! SEPatientListCell
        cell.delegate = self
        cell.updateCell(viewModel: viewModel.patientListItem(indexPath: indexPath), indexPath: indexPath)
        return cell
    }

    // MARK: - UITableViewDelegate

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = UIColor.clear
        return view
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard patientListType == .select else {
            return
        }
        selectedHandler?(viewModel.patientListItem(indexPath: indexPath))
        navigationController?.popViewController(animated: true)
    }

}

// MARK: - SERegistrationConfirmBtnViewDelegate

extension SEPatientListViewController: SERegistrationConfirmBtnViewDelegate {
    func registrationConfirmBtnViewAction(view: SERegistrationConfirmBtnView) {
        pushToPatientDetailViewController(.add)
    }
}

extension SEPatientListViewController: SEPatientListCellDelegate {
    func patientListCellBtnAction(actionType: SEPatientListCellBtnActionType, indexPath: IndexPath) {
        let model = viewModel.patientListItem(indexPath: indexPath)
        viewModel.selectedlistItem = model
        switch actionType {
        case .edit:
            pushToPatientDetailViewController(.edit)
        case .chooseDefault:
            requestSetDefaultPatient()
        }
    }
}

// MARK: APIRequest

extension SEPatientListViewController {
    @objc private func requestPatientList() {
        viewModel.requestPatientList()
    }

    @objc private func requestSetDefaultPatient() {
        viewModel.requestSetDefaultPatient()
    }
}
